#author: Piotr Falandysz

import fileinput

class GraphDataError(Exception):
	"""Wyjatek dla klasy Graph. Niepoprawna ilosc danych."""
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return `self.value`
		
class GraphDistanceError(Exception):
	"""Wyjatek dla klasy Graph. Niepoprawna odleglosc."""
	def __init__(self, value):
		self.value = value
	def __str__(self):
		return `self.value`

class Edge:
	"""Klasa reprezentujaca krawedz grafu."""
	def __init__(self, v1, v2, weight):
		self.v1 = v1
		self.v2 = v2
		self.weight = weight
		
	def getVertex1(self):
		return self.v1
		
	def getVertex2(self):
		return self.v2
		
	def getWeight(self):
		return self.weight
	
class Graph:
	"""Klasa reprezentujaca graf."""
	def __init__(self):
		self.graph = {}
		
	def __str__(self):
		res = ""
		for x in self.graph.items():
			res += str(x) + "\n"	
		return res
		
	def __repr__(self):
		return repr(self.graph)
		
	def add_edge(self, edge):
		"""Dodaje krawedz do grafu"""
		if edge.getVertex1() not in self.graph:
			self.graph[edge.getVertex1()] = []
		
		self.graph[edge.getVertex1()].append((edge.getVertex2(), int(edge.getWeight())))
	
	def getV(self):
		"""Zwraca wszystkie wierzcholki grafu"""
		return self.graph.keys()
		
	def load_from_file(self, file_name):
		"""Funkcja tworzy graf z danych zawartych w pliku .txt."""
		for line in fileinput.input([file_name]):
			words = line.split('" "')
			l = []
			for x in words:
				l.append(x.replace('"', '').replace("\n", ''))

			if l[0] == "edge" and len(l) == 4:
				if(int(l[3]) < 0):
					raise GraphDistanceError("Odleglosc miedzy miastami nie moze byc ujemna. Bledna linia: " + str(l))
				
				edge = Edge(l[1], l[2], l[3])
				self.add_edge(edge)
				edge = Edge(l[2], l[1], l[3])
				self.add_edge(edge)
			else:
				raise GraphDataError("Niepoprawne dane w pliku wejsciowym. Spodziewanych elementow 4 - otrzymano " + str(len(l)) + ". Bledna linia: " + str(l))